package com.zhw.task;

import com.zhw.mapper.CustomerMapper;
import com.zhw.pojo.entry.Customer;
import com.zhw.pojo.entry.CustomerLoss;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Component
public class LossTask {

    @Autowired
    CustomerMapper customerMapper;

//    @Scheduled(cron = "0/5 * * * * ? ")
    @Scheduled(cron = "0 0 0 1/1 * ?  ")
    //每天凌晨执行一次，检查有无客户要被沦为流失客户
    public void checkLose(){
        System.out.println("流失客户判定执行");

        //流失用户ID集合
        List<Integer> ids1=customerMapper.getLossId();

        List<Integer> ids2=customerMapper.getLossalreadyExistsId();

        List<Integer> ids=new ArrayList<>();
        ids.addAll(ids1);
        ids.addAll(ids2);

        List<Customer> list=customerMapper.getLossCustomer(ids);
        List<CustomerLoss> losses=new ArrayList<>();
        //获取到所有满足流失客户标准的客户（六个月未曾下单的），并将其转换为CustomerLoss的标准格式，并实现批量插入
        for (Customer customer : list) {
            CustomerLoss customerLoss=new CustomerLoss();
            customerLoss.setCusName(customer.getName());
            customerLoss.setStatus(0);
            customerLoss.setCusNo(customer.getKhno());
            customerLoss.setLossReason("六个月未下单");
            customerLoss.setCusManager(customer.getCusManager());
            customerLoss.setIsValid(0);
            customerLoss.setCreateDate(LocalDateTime.now());
            customerLoss.setUpdateDate(LocalDateTime.now());
            //获取到当前客户的最后下单时间
            customerLoss.setLastOrderTime(customerMapper.getLastOrderTimeById(customer.getId()));

            losses.add(customerLoss);

        }

        if (losses!=null&&losses.size()>0){
            customerMapper.insertLose(losses);
        }


    }

}
